<?php
namespace app\flash\controller;

use redis\RedisPackage;
use think\Controller;
use think\facade\Request;

class Base extends Controller
{
    public $user;
    /**
     * 验证登录
     */
    public function __construct()
    {
        parent::__construct();
        RedisPackage::getInstance();
        $headers = Request::instance()->header();
        if(isset($headers['token'])){
            $token = trim($headers['token']);
        }else{
            $t = input('token');
            if(!empty($t)){
                $token = $t;
            }else{
                echo json_encode([
                    'status' => 404,
                    'msg' => '缺少必要的参数'
                ]);
                exit();
            }
        }
        if (!$token) {
            header('Content-type: application/json');
            echo json_encode([
                'status' => 404,
                'msg' => '还没登陆，请先登录'
            ]);
            exit();
        }else{
            $user_id = substr($token, 32);
            $key = 'ht_'.$user_id;
            $token2 = RedisPackage::get($key);
            if(empty($token2)){
                echo json_encode([
                    'status' => 404,
                    'msg' => '登录已过期'
                ]);
                exit();
            }else{
                if($token != $token2 ){
                    echo json_encode([
                        'status' => 404,
                        'msg' => '请重新登录'
                    ]);
                    exit();
                }else{
                    RedisPackage::set($key, $token, 86400);
                    $this->user = db('user')->where(array('id'=>$user_id))->field('id,username,phone,picture,rand_id')->find();
                }
            }
        }
    }
}
